package controller;

import dao.UserDAO;
import model.User;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException {

        // 设置响应类型和编码
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        // 获取参数（建议增加trim()去除空格）
        String username = request.getParameter("username") != null ? request.getParameter("username").trim() : null;
        String email = request.getParameter("email") != null ? request.getParameter("email").trim() : null;
        String password = request.getParameter("password");

        try (PrintWriter out = response.getWriter()) {
            // 验证参数
            if (username == null || username.isEmpty() ||
                    email == null || email.isEmpty() ||
                    password == null || password.isEmpty()) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST); // 400
                out.print("{\"success\": false, \"message\": \"所有字段必须填写\"}");
                return;
            }

            // 邮箱格式验证（简单版）
            if (!email.matches("^[\\w-.]+@([\\w-]+\\.)+[\\w-]{2,4}$")) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST); // 400
                out.print("{\"success\": false, \"message\": \"邮箱格式不正确\"}");
                return;
            }

            UserDAO userDAO = new UserDAO();

            // 检查邮箱是否已存在
            if (userDAO.isEmailExists(email)) {
                response.setStatus(HttpServletResponse.SC_CONFLICT); // 409
                out.print("{\"success\": false, \"message\": \"该邮箱已被注册\"}");
                return;
            }

            // 注册用户（建议在实际项目中加密密码）
            User newUser = new User(username, email, password);
            if (userDAO.registerUser(newUser)) {
                response.setStatus(HttpServletResponse.SC_CREATED); // 201
                out.print("{\"success\": true, \"message\": \"注册成功\"}");
            } else {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); // 500
                out.print("{\"success\": false, \"message\": \"注册失败，请稍后再试\"}");
            }
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); // 500
            response.getWriter().print("{\"success\": false, \"message\": \"服务器错误\"}");
            e.printStackTrace(); // 实际项目中应使用日志记录
        }
    }
}